package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.example.bean.crm.jxsb;
import com.example.service.crmService.crmService;
import com.example.service.k3Service.k3Service;
import com.example.utils.k3Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Map;

/**
 * 经销商模块
 * Created by tony on 2017/12/15.
 */
@Component
@RestController
public class jxsControl {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    //定义k3Service
    @Autowired
    private k3Service k3Service;
    //定义mesService
    @Autowired
    private crmService crmService;
    public String token = "";

    /**
     * 获取Token
     */
    @RequestMapping("/GetToken")
    public boolean GetToken() {
        k3Api k3Api = new k3Api();
        String getTokenResult = k3Api.getToken();
        //解析结果
        Map result = (Map) JSON.parse(getTokenResult);
        if (result.get("StatusCode").toString().equals("200")) {
            Map data = (Map) JSON.parse(result.get("Data").toString());
            //设置token值
            token = data.get("Token").toString();
            logger.info("Token取得成功，token值：" + token);
            return true;
        } else {
            logger.info("Token取得失败，请检查网络");
            return false;
        }
    }

    /**
     * 经销商更新
     */
    @RequestMapping("/Jxs")
    @Scheduled(cron = "0 0/60 * * * ?") //经销商更新每小时
    public void insertJxsScheduled() {
        logger.info("经销商更新每天凌晨1点执行一次。开始……");
        try {
            //取得更新的经销商信息
            ArrayList<jxsb> jxsbList = crmService.selectJxs();
            //判断更新和新建经销商
            for (jxsb jxsb : jxsbList) {
                //是否已存入erp
                String erpFlg = jxsb.getERPid();
                //更新
                if (erpFlg == null || erpFlg.isEmpty() || erpFlg.equals("")) {
                    //新增
                    insertJxs(jxsb);
                } else {
                    //更新
                    k3Service.updateJsx(jxsb);
                    //已经更新添加
                    jxsb.setERPclyf(2);
                    //返回信息
                    jxsb.setRtnInfo("更新成功！");
                    logger.info(jxsb.getERPdaima()+"经销商更新成功！");
                    //返回处理结果
                    crmService.jxsFlagRturn(jxsb);
                }
            }

        } catch (Exception e) {
            logger.info(e.getMessage());

        }
        logger.info("经销商更新每天凌晨1点执行一次。结束。");

    }

    /**
     * erp中添加经销商
     */
    @RequestMapping("/insertJxs")
    public void insertJxs(jxsb jxsb) {
        if (GetToken()) {
            //new
            k3Api k3Api = new k3Api();
            //操作url
            String operation = "Customer/Save";
            try {
                // region crm表中取得数据
                String daima = jxsb.getERPdaima();
                String name = jxsb.getName();
                String shr = jxsb.getShr();
                String dizhi = jxsb.getDizhi();
                String ghdw2 = jxsb.getGhdw2();
                String zyywydaima = jxsb.getZyywydaima();
                String zyywyname = jxsb.getZyywyname();
                //分管部门
                String fgbm = jxsb.getFgbm();
                String fgbmNumber = "";
                if (fgbm != null || !fgbm.equals("")) {
                    Map<String, String> FDept = k3Service.selectBm(fgbm);
                    //部门编号
                    fgbmNumber = FDept.get("FNumber");
                }

//                String daima = "888888";
//                String name = "测试物料244";
//                String shr = "333333";
//                String dizhi = "333333";
//                String ghdw2 = "34454545";
//                String zyywydaima = "0001";
//                String zyywyname = "商若云";
                //endregion
                // region josn
                String param = "{" +
                        "  \"Data\": {" +
                        "    \"F_102\": \"" + shr + "\"," +
                        "    \"F_104\": \"" + ghdw2 + "\"," +
                        "    \"FAccount\": null," +
                        "    \"FAddrEn\": null," +
                        "    \"FAddress\": \"" + dizhi + "\"," +
                        "    \"FAPAccountID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FARAccountID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FBank\": null," +
                        "    \"FCarryingAOS\": 0," +
                        "    \"FCIQCode\": null," +
                        "    \"FCIQNumber\": null," +
                        "    \"FCityID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FContact\": null," +
                        "    \"Fcorperate\": null," +
                        "    \"FCoSupplierID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FCountry\": null," +
                        "    \"FCyID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FdebtLevel\": {" +
                        "      \"FID\": \"\"," +
                        "      \"FName\": \"\"" +
                        "    }," +
                        "    \"Fdepartment\": {" +
                        "      \"FName\": \"" + fgbm + "\"," +
                        "      \"FNumber\": \"" + fgbmNumber + "\"" +
                        "    }," +
                        "    \"FEmail\": null," +
                        "    \"Femployee\": {" +
                        "      \"FName\": \"" + zyywyname + "\"," +
                        "      \"FNumber\": \"" + zyywydaima + "\"" +
                        "    }," +
                        "    \"FfavorPolicy\": null," +
                        "    \"FFax\": null," +
                        "    \"FHelpCode\": null," +
                        "    \"FHomePage\": null," +
                        "    \"FIsCreditMgr\": false," +
                        "    \"FlastReceiveDate\": null," +
                        "    \"FlastRPAmount\": 0," +
                        "    \"FlastTradeAmount\": 0," +
                        "    \"FlastTradeDate\": null," +
                        "    \"FManageType\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FmaxDealAmount\": 0," +
                        "    \"FminForeReceiveRate\": 0," +
                        "    \"FminReserverate\": 0," +
                        "    \"FMobilePhone\": \"\"," +
                        "    \"FName\": \"" + name + "\"," +
                        "    \"FNameEN\": \"\"," +
                        "    \"FNumber\": \"" + daima + "\"," +
                        "    \"FOtherAPAcctID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FOtherARAcctID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FPayCondition\": [" +
                        "      {" +
                        "        \"FName\": \"\"," +
                        "        \"FNumber\": \"\"" +
                        "      }" +
                        "    ]," +
                        "    \"FPayTaxAcctID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FPhone\": null," +
                        "    \"FPostalCode\": null," +
                        "    \"FPreAcctID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FPreAPAcctID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FProvinceID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FRegion\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FRegionID\": {" +
                        "      \"FID\": \"\"," +
                        "      \"FName\": \"\"" +
                        "    }," +
                        "    \"FSaleID\": {" +
                        "      \"FID\": \"\"," +
                        "      \"FName\": \"\"" +
                        "    }," +
                        "    \"FSaleMode\": {" +
                        "      \"FID\": \"SIN\"," +
                        "      \"FName\": \"内销\"" +
                        "    }," +
                        "    \"FSetID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FShortName\": null," +
                        "    \"FStatus\": {" +
                        "      \"FID\": \"ZT01\"," +
                        "      \"FName\": \"使用\"" +
                        "    }," +
                        "    \"FStockIDKeep\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FTaxNum\": null," +
                        "    \"FTrade\": {" +
                        "      \"FID\": \"\"," +
                        "      \"FName\": \"\"" +
                        "    }," +
                        "    \"FTypeID\": {" +
                        "      \"FID\": \"\"," +
                        "      \"FName\": \"\"" +
                        "    }," +
                        "    \"FValueAddRate\": 0" +
                        "  }" +
                        "}";
                //endregion
                //解析结果
                Map result = (Map) JSON.parse(k3Api.callK3Api(operation, token, param));
                logger.info(result.toString());
                if (result.get("StatusCode").toString().equals("200")) {
                    //已经成功添加
                    jxsb.setERPclyf(2);
                    JSONArray jsonArray = JSONArray.parseArray(result.get("Data").toString());
                    Map information = jsonArray.getJSONObject(0);
                    //返回erpid
                    jxsb.setERPid(information.get("FItemID").toString());
                    //返回信息
                    jxsb.setRtnInfo("添加成功！");
                    logger.info(jxsb.getERPdaima()+"经销商新增成功！");
                } else {
                    //添加失败
                    jxsb.setERPclyf(3);
                    //返回信息
                    jxsb.setRtnInfo(result.get("Message").toString());
                    logger.error(jxsb.getERPdaima()+"经销商新增失败！");
                }
            } catch (Exception e) {
                //异常
                jxsb.setERPclyf(3);
                //返回信息
                jxsb.setRtnInfo("异常操作，请联系管理员");
            }
            crmService.jxsFlagRturn(jxsb);
        }

    }

    /**
     * erp中添加经销商
     */
    @RequestMapping("/updateJxs")
    public void updateJxs(jxsb jxsb) {
        if (GetToken()) {
            //new
            k3Api k3Api = new k3Api();
            //操作url
            String operation = "Customer/Update";
            try {
                // region crm表中取得数据
                String daima = jxsb.getERPdaima();
                String name = jxsb.getName();
                String shr = jxsb.getShr();
                String dizhi = jxsb.getDizhi();
                String ghdw2 = jxsb.getGhdw2();
                String zyywydaima = jxsb.getZyywydaima();
                String zyywyname = jxsb.getZyywyname();
                //分管部门
                String fgbm = jxsb.getFgbm();
                Map<String, String> FDept = k3Service.selectBm(fgbm);
                //部门编号
                String fgbmNumber = FDept.get("FNumber");
                //取客户旧编号
                Map<String, String> customer = k3Service.selectCustomer(jxsb.getERPid());
                String oldDaima = customer.get("FNumber");
//                String daima = "1099887";
//                String name = "测试物料";
//                String shr = "333333";
//                String dizhi = "333333";
//                String ghdw2 = "34454545";
//                String zyywydaima = "0001";
//                String zyywyname = "商若云";
                //endregion
                // region josn
                String param = "{" +
                        "  \"Data\": {" +
                        "    \"FNumber\": \"" + oldDaima + "\"," +
                        "  \"Data\": {" +
                        "    \"F_102\": \"" + shr + "\"," +
                        "    \"F_104\": \"" + ghdw2 + "\"," +
                        "    \"FAccount\": null," +
                        "    \"FAddrEn\": null," +
                        "    \"FAddress\": \"" + dizhi + "\"," +
                        "    \"FAPAccountID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FARAccountID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FBank\": null," +
                        "    \"FCarryingAOS\": 0," +
                        "    \"FCIQCode\": null," +
                        "    \"FCIQNumber\": null," +
                        "    \"FCityID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FContact\": null," +
                        "    \"Fcorperate\": null," +
                        "    \"FCoSupplierID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FCountry\": null," +
                        "    \"FCyID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FdebtLevel\": {" +
                        "      \"FID\": \"\"," +
                        "      \"FName\": \"\"" +
                        "    }," +
                        "    \"Fdepartment\": {" +
                        "      \"FName\": \"" + fgbm + "\"," +
                        "      \"FNumber\": \"" + fgbmNumber + "\"" +
                        "    }," +
                        "    \"FEmail\": null," +
                        "    \"Femployee\": {" +
                        "      \"FName\": \"" + zyywyname + "\"," +
                        "      \"FNumber\": \"" + zyywydaima + "\"" +
                        "    }," +
                        "    \"FfavorPolicy\": null," +
                        "    \"FFax\": null," +
                        "    \"FHelpCode\": null," +
                        "    \"FHomePage\": null," +
                        "    \"FIsCreditMgr\": false," +
                        "    \"FlastReceiveDate\": null," +
                        "    \"FlastRPAmount\": 0," +
                        "    \"FlastTradeAmount\": 0," +
                        "    \"FlastTradeDate\": null," +
                        "    \"FManageType\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FmaxDealAmount\": 0," +
                        "    \"FminForeReceiveRate\": 0," +
                        "    \"FminReserverate\": 0," +
                        "    \"FMobilePhone\": \"\"," +
                        "    \"FName\": \"" + name + "\"," +
                        "    \"FNameEN\": \"\"," +
                        "    \"FNumber\": \"" + daima + "\"," +
                        "    \"FOtherAPAcctID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FOtherARAcctID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FPayCondition\": [" +
                        "      {" +
                        "        \"FName\": \"\"," +
                        "        \"FNumber\": \"\"" +
                        "      }" +
                        "    ]," +
                        "    \"FPayTaxAcctID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FPhone\": null," +
                        "    \"FPostalCode\": null," +
                        "    \"FPreAcctID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FPreAPAcctID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FProvinceID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FRegion\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FRegionID\": {" +
                        "      \"FID\": \"\"," +
                        "      \"FName\": \"\"" +
                        "    }," +
                        "    \"FSaleID\": {" +
                        "      \"FID\": \"\"," +
                        "      \"FName\": \"\"" +
                        "    }," +
                        "    \"FSaleMode\": {" +
                        "      \"FID\": \"SIN\"," +
                        "      \"FName\": \"内销\"" +
                        "    }," +
                        "    \"FSetID\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FShortName\": null," +
                        "    \"FStatus\": {" +
                        "      \"FID\": \"ZT01\"," +
                        "      \"FName\": \"使用\"" +
                        "    }," +
                        "    \"FStockIDKeep\": {" +
                        "      \"FName\": \"\"," +
                        "      \"FNumber\": \"\"" +
                        "    }," +
                        "    \"FTaxNum\": null," +
                        "    \"FTrade\": {" +
                        "      \"FID\": \"\"," +
                        "      \"FName\": \"\"" +
                        "    }," +
                        "    \"FTypeID\": {" +
                        "      \"FID\": \"\"," +
                        "      \"FName\": \"\"" +
                        "    }," +
                        "    \"FValueAddRate\": 0" +
                        "  }" +
                        "  }" +
                        "}";
                //endregion
                //解析结果
                Map result = (Map) JSON.parse(k3Api.callK3Api(operation, token, param));
                logger.info(result.toString());
                if (result.get("StatusCode").toString().equals("200")) {
                    //已经更新添加
                    jxsb.setERPclyf(2);
                    //返回信息
                    jxsb.setRtnInfo("更新成功！");
                    logger.info("经销商更新成功！");
                } else {
                    jxsb.setERPclyf(3);
                    //返回信息
                    jxsb.setRtnInfo(result.get("Message").toString());
                    logger.info(result.get("Message").toString());
                }
            } catch (Exception e) {
                jxsb.setERPclyf(3);
                //返回信息
                jxsb.setRtnInfo("异常操作，请联系管理员");
                logger.info(e.getMessage());
            }
            //返回处理结果
            crmService.jxsFlagRturn(jxsb);

        }

    }


}
